/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.easoft.code.pos.util;

import java.awt.print.PrinterException;
import java.awt.print.PrinterJob;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.print.Doc;
import javax.print.DocFlavor;
import javax.print.DocPrintJob;
import javax.print.PrintException;
import javax.print.PrintService;
import javax.print.PrintServiceLookup;
import javax.print.SimpleDoc;
import javax.print.attribute.HashPrintRequestAttributeSet;
import javax.print.attribute.PrintRequestAttributeSet;
import javax.print.attribute.standard.Copies;
import javax.print.attribute.standard.MediaPrintableArea;
import javax.print.attribute.standard.MediaSize;
import javax.print.attribute.standard.MediaSizeName;
import javax.print.attribute.standard.OrientationRequested;
import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JRExporter;
import net.sf.jasperreports.engine.JRExporterParameter;
import net.sf.jasperreports.engine.JasperCompileManager;
import net.sf.jasperreports.engine.JasperExportManager;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.JasperReport;
import net.sf.jasperreports.engine.export.JRPdfExporter;
import net.sf.jasperreports.engine.export.JRPdfExporterParameter;
import net.sf.jasperreports.engine.export.JRPrintServiceExporter;
import net.sf.jasperreports.engine.export.JRPrintServiceExporterParameter;
import net.sf.jasperreports.engine.util.FileResolver;
import net.sf.jasperreports.engine.util.JRSaver;

/**
 *
 * @author Eliu
 */
public class Printer {

    /**
     * Devuelve interfaz de reporte para mostrarlo en panel
     *
     * @param reportInstance
     * @param par
     * @return
     * @throws EaPosPrintingException
     */
    public static JasperPrint getReportPrinter(InputStream reportInstance, Map par) throws EaPosPrintingException {
        Connection conn = null;
        try {
            par.put("REPORT_FILE_RESOLVER", new FileResolver() {
                @Override
                public File resolveFile(String fileName) {
                    return new File(ClassLoader.getSystemResource(fileName).getPath());
                }
            });
            conn = DBConnection.getConnection();
            JasperReport compileReport = JasperCompileManager.compileReport(reportInstance);
            JasperPrint jp = JasperFillManager.fillReport(compileReport, par, conn);
            return jp;
        } catch (JRException | SQLException e) {
            e.printStackTrace(System.err);
            throw new EaPosPrintingException(e);
        } finally {
            if (conn != null) {
                try {
                    conn.close();
                } catch (SQLException ex) {
                    ex.printStackTrace(System.err);
                }
            }
        }
    }

    public void loadReportMasivo(String path, Map par, String jrxmlfile, String htmlName, String factura) {
        try {
            Connection conn = DBConnection.getConnection();
            String d = System.getProperty("file.separator");
            File jd = new File(path + d + jrxmlfile);
            JasperPrint jp = JasperFillManager.fillReport(jd.getPath(), par, conn);
            JasperExportManager.exportReportToPdfFile(jp, path + d + factura);

            final JRExporter jtrtf = new JRPdfExporter();
            jtrtf.setParameter(JRPdfExporterParameter.IS_ENCRYPTED, Boolean.TRUE);
            jtrtf.setParameter(JRPdfExporterParameter.IS_128_BIT_KEY, Boolean.TRUE);
            jtrtf.setParameter(JRExporterParameter.JASPER_PRINT, jp);
            JRSaver.saveObject(jp, "c:/factura.jrprint");
            jtrtf.setParameter(JRExporterParameter.OUTPUT_FILE_NAME, "c:/prueba.pdf");
            jtrtf.exportReport();
            print(path + "/prueba.pdf");
        } catch (SQLException | JRException | FileNotFoundException | PrintException e) {
            e.printStackTrace();
        }
    }

    public static void print(String file) throws FileNotFoundException, PrintException {
        InputStream is = new BufferedInputStream(new FileInputStream(file));
        DocFlavor flavor = DocFlavor.INPUT_STREAM.PDF;
        PrintService service = PrintServiceLookup.lookupDefaultPrintService();
        DocPrintJob printJob = service.createPrintJob();
        Doc doc = new SimpleDoc(is, flavor, null);
        PrintRequestAttributeSet attributes = new HashPrintRequestAttributeSet();
        attributes.add(OrientationRequested.PORTRAIT);
        printJob.print(doc, attributes);
    }

    public static void printReport(String file_name, String serie, String numero, String valorLetras) {
        InputStream is = null;
        try {
            Map<String, Object> mapa = new HashMap<>();
            mapa.put("fserie", serie);
            mapa.put("fnumero", numero);
            mapa.put("fvalorletras", valorLetras);
            String Report = Valores.getCAEConfigValue("reporte.factura") + file_name + ".jasper";//my Jasper report file
            is = new FileInputStream(new File(Report));
            JasperPrint print = JasperFillManager.fillReport(is, mapa, DBConnection.getConnection());
            PrinterJob job = PrinterJob.getPrinterJob();
            /* Create an array of PrintServices */
            PrintService[] services = PrintServiceLookup.lookupPrintServices(null, null);
            int selectedService = 0;
            /* Scan found services to see if anyone suits our needs *
             for(int i = 0; i < services.length;i++)
             {
             if(services[i].getName().toUpperCase().contains("Your printer's name"))
             {
             If the service is named as what we are querying we select it 
             selectedService = i;
             }
             }*/
            job.setPrintService(services[selectedService]);
            PrintRequestAttributeSet printRequestAttributeSet = new HashPrintRequestAttributeSet();
            MediaSizeName mediaSizeName = MediaSize.findMedia(4, 4, MediaPrintableArea.INCH);
            printRequestAttributeSet.add(mediaSizeName);
            printRequestAttributeSet.add(new Copies(1));
            JRPrintServiceExporter exporter;
            exporter = new JRPrintServiceExporter();
            exporter.setParameter(JRExporterParameter.JASPER_PRINT, print);
            /* We set the selected service and pass it as a paramenter */
            exporter.setParameter(JRPrintServiceExporterParameter.PRINT_SERVICE, services[selectedService]);
            exporter.setParameter(JRPrintServiceExporterParameter.PRINT_SERVICE_ATTRIBUTE_SET, services[selectedService].getAttributes());
            exporter.setParameter(JRPrintServiceExporterParameter.PRINT_REQUEST_ATTRIBUTE_SET, printRequestAttributeSet);
            exporter.setParameter(JRPrintServiceExporterParameter.DISPLAY_PAGE_DIALOG, Boolean.FALSE);
            exporter.setParameter(JRPrintServiceExporterParameter.DISPLAY_PRINT_DIALOG, Boolean.TRUE);
            exporter.exportReport();
        } catch (FileNotFoundException ex) {
            Logger.getLogger(Printer.class.getName()).log(Level.SEVERE, null, ex);
        } catch (SQLException ex) {
            Logger.getLogger(Printer.class.getName()).log(Level.SEVERE, null, ex);
        } catch (PrinterException | JRException ex) {
            Logger.getLogger(Printer.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            try {
                is.close();
            } catch (IOException ex) {
                Logger.getLogger(Printer.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }
}
